<template>
  <view :class="{'schedule-registration-container': !isLandscape}">
	  <template v-if="!isLandscape">
		<!-- 页面头部 -->
		<view class="page-header">
		  <button class="back-btn" @click="goBack">← 返回</button>
		  <div class="page-title">报名情况</div>
		</view>

		<!-- 赛程信息 -->
		<view class="schedule-info-section">
		  <div class="card">
			<div class="card-header">
			  <div class="title">赛程信息</div>
			</div>
			<div class="info-content">
			  <div class="info-row">
				<div class="info-label">赛程名称:</div>
				<div class="info-value">{{ scheduleName }}</div>
			  </div>
			  <div class="info-row">
				<div class="info-label">赛程ID:</div>
				<div class="info-value">{{ scheduleId }}</div>
			  </div>
			  <div class="info-row">
				<div class="info-label">报名人数:</div>
				<div class="info-value registration-count">{{ registrationList.length }} 人</div>
			  </div>
			</div>
		  </div>
		</view>

		<!-- 报名列表 -->
		<view class="registration-list-section">
		  <div class="card">
			<div class="card-header">
			  <div class="title">报名记录</div>
			  <div class="header-actions">
				<button class="refresh-btn" @click="loadRegistrationList" :disabled="loading">
				  {{ loading ? '刷新中...' : '刷新' }}
				</button>
			  </div>
			</div>
			
			<div v-if="loading" class="loading-container">
			  <div class="loading-spinner"></div>
			  <text>加载中...</text>
			</div>
			
			<div v-else-if="registrationList.length === 0" class="empty-state">
			  <text>暂无报名记录</text>
			</div>
			
			<div v-else class="registration-list">
			  <div 
				class="registration-item" 
				v-for="registration in registrationList" 
				:key="registration.id"
			  >
				<div class="registration-header">
				  <div class="registration-id">报名ID: {{ registration.id }}</div>
				  <div class="registration-status" :class="getStatusClass(registration.delFlag)">
					{{ getStatusText(registration.delFlag) }}
				  </div>
				</div>
				
				<div class="registration-info">
				  <div class="info-row">
					<div class="info-label">用户ID:</div>
					<div class="info-value">{{ registration.userId || '未知' }}</div>
				  </div>
				  <div class="info-row">
					<div class="info-label">赛程ID:</div>
					<div class="info-value">{{ registration.matchScheduleId }}</div>
				  </div>
				  <div class="info-row">
					<div class="info-label">报名时间:</div>
					<div class="info-value">{{ formatDate(registration.createTime) }}</div>
				  </div>
				  <div class="info-row">
					<div class="info-label">更新时间:</div>
					<div class="info-value">{{ formatDate(registration.updateTime) }}</div>
				  </div>
				</div>
				
				<div class="registration-actions">
				  <button class="edit-btn" @click="editRegistration(registration)">编辑</button>
				  <button class="delete-btn" @click="deleteRegistration(registration)">删除</button>
				</div>
			  </div>
			</div>
		  </div>
		</view>
	</template>
	
	<!-- 横屏展示的内容 -->
	<LandscapePage 
	v-else 
	:formBtns="formBtns" 
	:currentIndex="currentIndex" 
	:setCurrentIndex="setCurrentIndex"
	:data="registrationList"
	:scheduleName="scheduleName"
	:scheduleId="scheduleId"
	:formItems="formItems"
	:loading="loading"></LandscapePage>

    <!-- 编辑报名记录模态框 -->
    <view class="modal-overlay" v-if="showEditModal" @click="closeEditModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">编辑报名记录</text>
          <button class="close-btn" @click="closeEditModal">×</button>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">用户ID</text>
            <input 
              class="form-input" 
              v-model="editForm.userId" 
              placeholder="请输入用户ID"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeEditModal">取消</button>
          <button class="submit-btn" @click="submitEdit" :disabled="submitting">
            {{ submitting ? '提交中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchScheduleRegAPI } from '@/api/battle.js'
import useIsLandscape from '@/composables/useIsLandscape.js'
import LandscapePage from '@/views/landscape/schedule-registration.vue'

const { isLandscape } = useIsLandscape()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const scheduleId = ref('')
const scheduleName = ref('')
const registrationList = ref([])

// 编辑模态框相关
const showEditModal = ref(false)
const editForm = ref({
  matchScheduleRegId: '',
  matchScheduleId: '',
  userId: ''
})
const currentRegistration = ref(null)

// 状态映射
const statusMap = {
  0: '有效',
  1: '已删除'
}

const statusClassMap = {
  0: 'status-valid',
  1: 'status-deleted'
}

// 获取状态文本
const getStatusText = (delFlag) => statusMap[delFlag] || '未知'

// 获取状态样式
const getStatusClass = (delFlag) => statusClassMap[delFlag] || 'status-unknown'

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 加载报名列表
const loadRegistrationList = async () => {
  if (!scheduleId.value) return
  setCurrentIndex(0)
  loading.value = true
  try {
    console.log('加载报名列表，赛程ID:', scheduleId.value)
    
    const result = await MatchScheduleRegAPI.page({
      matchScheduleId: scheduleId.value,
      pageNum: 0,
      pageSize: 100
    })
    
    console.log('报名列表API返回结果:', result)
    
    if (result.code === 0) {
      registrationList.value = result.data || []
      console.log('获取到报名记录:', registrationList.value)
    } else {
      registrationList.value = []
      throw new Error(result.msg || '获取报名记录失败')
    }
  } catch (error) {
    console.error('获取报名记录失败:', error)
    uni.showToast({
      title: error.message || '获取报名记录失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 编辑报名记录
const editRegistration = (registration) => {
  currentRegistration.value = registration
  editForm.value = {
    matchScheduleRegId: registration.id,
    matchScheduleId: registration.matchScheduleId,
    userId: registration.userId || ''
  }
  showEditModal.value = true
}

// 删除报名记录
const deleteRegistration = (registration) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除报名记录 ${registration.id} 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchScheduleRegAPI.remove({
            matchScheduleRegId: registration.id
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            loadRegistrationList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除报名记录失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 关闭编辑模态框
const closeEditModal = () => {
  showEditModal.value = false
  editForm.value = {
    matchScheduleRegId: '',
    matchScheduleId: '',
    userId: ''
  }
  currentRegistration.value = null
}

// 提交编辑
const submitEdit = async () => {
  if (!editForm.value.userId.trim()) {
    uni.showToast({
      title: '请输入用户ID',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const result = await MatchScheduleRegAPI.edit(editForm.value)
    
    if (result.code === 0) {
      uni.showToast({
        title: '编辑成功',
        icon: 'success'
      })
      closeEditModal()
      loadRegistrationList()
    } else {
      throw new Error(result.msg || '编辑失败')
    }
  } catch (error) {
    console.error('编辑报名记录失败:', error)
    uni.showToast({
      title: error.message || '编辑失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面加载
onLoad((options) => {
  if (options.scheduleId) {
    scheduleId.value = options.scheduleId
  }
  if (options.scheduleName) {
    scheduleName.value = decodeURIComponent(options.scheduleName)
  }
})

// 页面挂载时加载数据
onMounted(() => {
  loadRegistrationList()
})

const formBtns = [
	{
		text: '编辑',
		icon: '/src/static/btn_blue.png',
		color: '#FFFFFF',
		click() {
			editRegistration(registrationList.value[currentIndex.value])
		}
	},
	{
		text: '删除',
		icon: '/src/static/btn_red.png',
		color: '#FFFFFF',
		click() {
			deleteRegistration(registrationList.value[currentIndex.value])
		}
	}
]

const formItems = [
	{
		label: '报名ID',
		key: 'id',
		format(val) {
			return val
		},
		status: {
			key: 'delFlag',
			className(val) {
				const className = getStatusClass(val)
				return 'registration-status' + (className ? ` ${className}` : '')
			},
			format(val) {
				return getStatusText(val)
			}
		}
	},
	{
		label: '用户ID',
		key: 'userId',
		format(val) {
			return val || '未知'
		}
	},
	{
		label: '赛程ID',
		key: 'matchScheduleId',
		format(val) {
			return val
		}
	},
	{
		label: '报名时间',
		key: 'createTime',
		format(val) {
			return formatDate(val)
		}
	},
	{
		label: '更新时间',
		key: 'updateTime',
		format(val) {
			return formatDate(val)
		}
	}
]

// 当前模式的索引
const currentIndex = ref(0)
const setCurrentIndex = (index) => currentIndex.value = index
</script>

<style lang="scss" scoped>
.schedule-registration-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

// 页面头部样式
.page-header {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
  
  .back-btn {
    background: none;
    border: none;
    color: #fff;
    font-size: 28rpx;
    padding: 10rpx 20rpx;
    margin-right: 20rpx;
  }
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
  }
}

// 赛程信息样式
.schedule-info-section {
  margin-bottom: 30rpx;
  
  .card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
    
    .card-header {
      margin-bottom: 20rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .info-content {
      .info-row {
        display: flex;
        margin-bottom: 15rpx;
        font-size: 26rpx;
        
        .info-label {
          width: 160rpx;
          color: #666;
          font-weight: 500;
        }
        
        .info-value {
          flex: 1;
          color: #333;
          
          &.registration-count {
            color: #667eea;
            font-weight: bold;
          }
        }
      }
    }
  }
}

// 报名列表样式
.registration-list-section {
  .card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .header-actions {
        .refresh-btn {
          height: 50rpx;
          padding: 0 20rpx;
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          border: none;
          border-radius: 8rpx;
          color: #fff;
          font-size: 24rpx;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
    
    .loading-container, .empty-state {
      text-align: center;
      padding: 40rpx;
      color: #666;
      
      .loading-spinner {
        width: 60rpx;
        height: 60rpx;
        border: 4rpx solid #f3f3f3;
        border-top: 4rpx solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 20rpx;
      }
    }
    
    .registration-list {
      .registration-item {
        background: #f8f9fa;
        border-radius: 12rpx;
        padding: 20rpx;
        margin-bottom: 15rpx;
        border: 1rpx solid #e9ecef;
        
        .registration-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15rpx;
          
          .registration-id {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
          }
          
          .registration-status {
            padding: 6rpx 16rpx;
            border-radius: 16rpx;
            font-size: 22rpx;
            font-weight: bold;
            
            &.status-valid {
              background: #d4edda;
              color: #155724;
            }
            
            &.status-deleted {
              background: #f8d7da;
              color: #721c24;
            }
          }
        }
        
        .registration-info {
          margin-bottom: 15rpx;
          
          .info-row {
            display: flex;
            margin-bottom: 8rpx;
            font-size: 24rpx;
            
            .info-label {
              width: 140rpx;
              color: #666;
            }
            
            .info-value {
              flex: 1;
              color: #333;
            }
          }
        }
        
        .registration-actions {
          display: flex;
          gap: 10rpx;
          
          .edit-btn, .delete-btn {
            flex: 1;
            height: 50rpx;
            border: none;
            border-radius: 8rpx;
            font-size: 24rpx;
            
            &.edit-btn {
              background: #007bff;
              color: #fff;
            }
            
            &.delete-btn {
              background: #dc3545;
              color: #fff;
            }
          }
        }
      }
    }
  }
}

// 模态框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    width: 90%;
    max-height: 80%;
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #eee;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        width: 60rpx;
        height: 60rpx;
        border: none;
        background: none;
        font-size: 40rpx;
        color: #999;
		line-height: 60rpx;
		margin: 0;
      }
    }
    
    .modal-body {
      padding: 30rpx;
      
      .form-item {
        margin-bottom: 30rpx;
        
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 15rpx;
          font-weight: bold;
        }
        
        .form-input {
          width: 100%;
          height: 80rpx;
          border: 2rpx solid #eee;
          border-radius: 12rpx;
          padding: 0 20rpx;
          font-size: 28rpx;
          background: #fff;
          box-sizing: border-box;
        }
      }
    }
    
    .modal-footer {
      display: flex;
      gap: 20rpx;
      padding: 30rpx;
      border-top: 2rpx solid #eee;
      
      .cancel-btn, .submit-btn {
        flex: 1;
        height: 80rpx;
        border: none;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: bold;
        
        &.cancel-btn {
          background: #f8f9fa;
          color: #666;
          border: 2rpx solid #eee;
        }
        
        &.submit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          color: #fff;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media screen and (orientation: landscape) {
	.modal-overlay {
		.modal-content {
			display: flex;
			max-height: 90vh;
			flex-direction: column;
			.modal-header {
				padding: 10rpx;
			}
			.modal-body {
				box-sizing: border-box;
				padding: 10rpx;
				max-height: 60vh;
				.form-item {
					margin-bottom: 0rpx;
				}
			}
			.modal-footer {
				padding: 10rpx;
				.cancel-btn, .submit-btn {
					height: 60rpx;
					line-height: 60rpx;
				}
			}
		}
	}
}
</style> 